﻿//使用反射技术，调用Person类的构造方法创建实例对象。

using System;
using System.Reflection;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person()
    {
        Name = "Unknown";
        Age = 0;
    }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 获取Person类的Type对象
        Type personType = typeof(Person);

        // 使用无参数的构造函数创建实例
        ConstructorInfo defaultConstructor = personType.GetConstructor(Type.EmptyTypes);
        if (defaultConstructor != null)
        {
            Person person1 = (Person)defaultConstructor.Invoke(null);
            Console.WriteLine($"Person1: Name = {person1.Name}, Age = {person1.Age}");
        }
        else
        {
            Console.WriteLine("No parameterless constructor found.");
        }

        // 使用有参数的构造函数创建实例
        ConstructorInfo parameterizedConstructor = personType.GetConstructor(new Type[] { typeof(string), typeof(int) });
        if (parameterizedConstructor != null)
        {
            Person person2 = (Person)parameterizedConstructor.Invoke(new object[] { "John Doe", 30 });
            Console.WriteLine($"Person2: Name = {person2.Name}, Age = {person2.Age}");
        }
        else
        {
            Console.WriteLine("No constructor found that matches the specified criteria.");
        }
    }
}
